//
//  MasterViewController.m
//  Iderun
//
//  Created by Zhou, Shaolin on 6/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AuditedViewController.h"
#import "XmlReader.h"
#import "MasterTableCell.h"
#import "DetailViewController.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "JSON.h"


@implementation AuditedViewController

@synthesize _tableView,resultData,mysearchBar;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
        }

        self.title = @"我已审批";
        self._tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }
    return self;
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData=[NSMutableArray array];
    CGRect rect=[[UIScreen mainScreen] bounds];
    rect.size.height=rect.size.height-[UIApplication sharedApplication].statusBarFrame.size.height-self.navigationController.navigationBar.frame.size.height-self.tabBarController.tabBar.frame.size.height;
    rect.origin.y=0;
    UITableView *tableView=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self._tableView=tableView;
    [_tableView  release];
    [self.view  addSubview:self._tableView];
    self._tableView.delegate=self;
    self._tableView.dataSource=self;
    if (requestManager == nil) {
        requestManager = [[UrlRequest alloc] initWithDelegate:self requestSelector:@selector(parseReceivedData:) errorSelector:@selector(errorCallback)];
    }
    
    UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithCustomView:[self customButtom:100 withFrame:CGRectMake(10, 0, 44, 28) action:@selector(logoutAction:) normalImage:@"btn_logOut.png" lightedImage:@"btn_logOut.png" title:@""]];
    leftButton.style = UIBarButtonItemStylePlain;
    self.navigationItem.leftBarButtonItem=leftButton;
    [leftButton release];
    
    
    
    UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    customButton.frame=CGRectMake(10, 0, 21, 44);
	[customButton addTarget:self action:@selector(reflush:) forControlEvents:UIControlEventTouchUpInside];
	[customButton setImage:[UIImage imageNamed:@"head_btn_update_off.png"] forState:UIControlStateNormal];
	[customButton setBackgroundImage:[UIImage imageNamed:@"head_btn_update_on.png"] forState:UIControlStateSelected];
    [customButton setBackgroundImage:[UIImage imageNamed:@"head_btn_update_on.png"] forState:UIControlStateHighlighted];
	UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:customButton];
    addButton.style = UIBarButtonItemStylePlain;
    self.navigationItem.rightBarButtonItem=addButton;
    [addButton release];
    
    //CustomSearchBar *_mySearchBar = [[CustomSearchBar alloc] initWithFrame:CGRectMake(0.0f, self._tableView.frame.origin.y - 44.0f, self.view.frame.size.width, 44.0f)];
    CustomSearchBar *_mySearchBar = [[CustomSearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)];
    [_mySearchBar setBarBackgroundImage:[UIImage imageNamed:@"title_bg.png"]];
    _mySearchBar.delegate = self;
    [_mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [_mySearchBar sizeToFit];
    [self._tableView addSubview:_mySearchBar];
    mysearchBar=_mySearchBar;
    [_mySearchBar  release];
    //self._tableView.contentInset = UIEdgeInsetsMake(44.0f, 0.0f, 0.0f, 0.0f);
    [self  loadData:@""];
    
}
-(void) hiddenNavBar:(BOOL) status{
//    [self.navigationController setNavigationBarHidden:status animated:YES];
//    if (!status) {
//        _tableView.contentInset=UIEdgeInsetsMake(44.0f, 0.0f, 0.0f, 0.0f);
//    }
}

-(IBAction)logoutAction:(id)sender{
    NSUserDefaults *userdefault= [NSUserDefaults standardUserDefaults];
    [userdefault setObject:nil forKey:@"USER_ID"];
    [userdefault  synchronize];
   // LoginViewController *login=[[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    //UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:login];
    //[login  release];
    AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;
    [appDelegate   popLoginViewController];
   // [nav  release];
}
-(void) viewWillAppear:(BOOL)animated{
    [super  viewWillAppear:animated];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"USER_ID"]==nil) {
        //LoginViewController *login=[[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
       // UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:login];
        //[login  release];
        AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;
        [appDelegate  popLoginViewController];
        //[appDelegate.tabbar presentModalViewController:nav animated:NO];
        //[nav  release];
        
    }
    

}
-(IBAction)reflush:(id)sender{
    [self  loadData:@""];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

-(void) loadData:(NSString*)keyWords{
    keyWords = [keyWords stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [MBProgressHUD  showHUDAddedTo:appdelegate.tabbar.view animated:NO];
    [requestManager requestToCheckList:1 andKeyWords:keyWords];
}

-(void)parseReceivedData:(id)data{
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [ MBProgressHUD  hideHUDForView:appdelegate.tabbar.view animated:NO];
    @try {
        if (data==nil||[data isEqualToString:@""]) {
            //NSLog(@"master receivedString=%@",@"空");
            
            return;
        }
        NSError **error;
        NSDictionary *result=[XmlReader dictionaryForXMLString:data error:error];
        [self.resultData removeAllObjects];
        id  resultDict= [[[[[[[result  objectForKey:@"soap:Envelope"] objectForKey:@"soap:Body"] objectForKey:@"GetDataSetSqlResponse"] objectForKey:@"GetDataSetSqlResult"] objectForKey:@"diffgr:diffgram"] objectForKey:@"NewDataSet"] objectForKey:@"Table"];
        if ([[resultDict JSONRepresentation] hasPrefix:@"{"]) {
            [self.resultData  addObject:resultDict];
        }else{
            self.resultData=[NSMutableArray  arrayWithArray:resultDict];
            
        }
    }@catch (NSException *exception) {
        NSLog(@"master主页加载数据:%@",[exception description]);
    }
    
    [self._tableView  reloadData];
}
-(void)errorCallback{
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [ MBProgressHUD  hideHUDForView:appdelegate.tabbar.view animated:NO];
    NSString* okTitle = @"提醒";
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"网路异常" delegate:nil cancelButtonTitle:okTitle otherButtonTitles:nil];
    [alert show];
    [alert release];
}

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.resultData  count];
}
- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.0f;
}

// Customize the appearance of table view cells.
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"masterTableCell";
    
    MasterTableCell *cell = (MasterTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MasterTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    [cell  showData:[self.resultData objectAtIndex:indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *detailViewController=[[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailViewController.itemDictory=[self.resultData  objectAtIndex:indexPath.row];
    //[detailViewController  showShenheButton];
    //[detailViewController loadImageFromURL];
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    [detailViewController  release];
}


/*
 -(void)loginSuccess
 {   AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;
 [appDelegate.tabbar dismissModalViewControllerAnimated:YES];
 [loginController release];
 loginController = nil;
 }*/

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsScopeBar = YES;
    [searchBar sizeToFit];
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [NSObject  cancelPreviousPerformRequestsWithTarget:self];
    [self  hiddenNavBar:YES];
    
    
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    searchBar.showsScopeBar = NO;
    [searchBar sizeToFit];
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    //NSLog(@"%@",@"searchBarTextDidEndEditing");
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self  hiddenNavBar:NO];
    [searchBar  resignFirstResponder];
    
    // NSLog(@"%@",@"searchBarCancelButtonClicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar  resignFirstResponder];
    [self  hiddenNavBar:NO];
    [self loadData:searchBar.text];
    
    
    //NSLog(@"searchBarSearchButtonClicked=%@",searchBar.text);
}

- (UIButton*) customButtom:(NSUInteger)numberOfTag withFrame:(CGRect)frame action:(SEL)action normalImage:(NSString*)normalImage lightedImage:(NSString*)lightedImage  title:(NSString *)title{
    UIButton* button;
    if (title==nil||[@"" isEqualToString:title]) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
    }else {
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:title forState:UIControlStateNormal];
    }
    
    button.frame = frame;
    button.tag=numberOfTag;
    button.backgroundColor=[UIColor clearColor];
    
    if (![normalImage isEqualToString:@""]) {
        UIImage *normal_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:normalImage ofType:nil]];
        [button setImage:normal_Image forState:UIControlStateNormal];
    }
    
    if (![lightedImage isEqualToString:@""]) {
        UIImage *lighted_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:lightedImage ofType:nil]];
        [button setImage:lighted_Image forState:UIControlStateHighlighted];
        [button setImage:lighted_Image forState:UIControlStateSelected];
    }
    
    button.adjustsImageWhenHighlighted = NO;
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation==UIDeviceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc{
    //[loginController release];
    [requestManager  release];
    [_tableView  release];
    [resultData  release];
    [mysearchBar release];
    [super dealloc];
}



@end
